#include "GetUnlockRequest.h"
#include "db/DBManager.h"

#include <QDebug>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QJsonObject>
#include <QSqlError>
#include <QJsonArray>

void GetUnlockRequest::handleSession()
{
    QMap<QString, QString> mapQuery = m_session->requestUrlQuery();

    QString strOpenId = mapQuery.value("openid");


    QStringList listDevNamesOfOpenId = getDeviceNameListByOpenId(strOpenId);

    QVariantList listRet;

    qDebug() << "in GetUnlockRequest: " << s_listRequstUnlock;

    qDebug() << "listDevNamesOfOpenId: " << listDevNamesOfOpenId;

    for (int i=0; i<s_listRequstUnlock.size(); ++i)
    {
        QMap<QString, QString> mapOne = s_listRequstUnlock.at(i);
        if (listDevNamesOfOpenId.contains(mapOne.value("device_name")))
        {
            QStringList keys = mapOne.keys();
            QVariantMap varMapOne;
            foreach (QString key, keys) {
                varMapOne.insert(key, mapOne.value(key));
            }
            listRet.append(varMapOne);
        }
    }

    QJsonArray arrayJson = QJsonArray::fromVariantList(listRet);

    m_session->replyJsonArray(arrayJson);
}

QStringList GetUnlockRequest::getDeviceNameListByOpenId(const QString &openId)
{
    QString strSql = QString("select szDeviceName from manager_device where szOpenId='%1'")
            .arg(openId);

    QSqlDatabase db = DBManager::database("core_config");
    QSqlQuery query(db);

    if(!query.exec(strSql))
    {
        qDebug()<<"exec select szDeviceName error, "<<query.lastError().text();
        return QStringList();
    }

    QStringList listRet;
    while(query.next())
    {
        listRet.append(query.value(0).toString());
    }

    return listRet;
}
